import * as NS from "../../Common/NetServices";
import { Wx_XSPPage, V_Cart } from "../../Common/Entitys";
import { Wx_PageData, WXDataClassRuntimeDecorator } from "../../Common/EntityBase";
import { WXIconType } from "../../wxAPI_";

@WXDataClassRuntimeDecorator()
class IndexPageData extends Wx_PageData {
    public CartList: Array<V_Cart> = new Array<V_Cart>();
    public TotalPrice: number = 0;
    public AllSelected: boolean = false;
    public Count: number = 0;
    public flag: boolean = false;
}

class IndexPage extends Wx_XSPPage {
    public Data: IndexPageData = new IndexPageData();

    async onShowAgain() {
        this.InitData(null);
    }

    /**
     * 初始化页面信息
     * @param {any} options
     * @returns {Promise<void>}
     * @memberof IndexPage
     */
    public async InitData(options: any): Promise<void> {
        try {
            wx.showToast({ title: "数据加载中.....", icon: WXIconType.loading });
            // 底部加载
            this.EditTabBar();
            this.App.CartList = await NS.QueryUserCart();
            console.log(this.App.CartList);
            let allSelected: boolean = true;
            this.App.CartList.forEach(el => {
                el.GOODS.SALESTARTTIME = el.GOODS.SALESTARTTIME.ToDate().Format(
                    "MM月dd日 hh:mm开始"
                );
                if (el.GOODSSTATUS == 1 && !el.ISSELECT) {
                    allSelected = false;
                }
            });
            this.Data.CartList = this.App.CartList;
            this.Data.AllSelected = allSelected;
            this.Data.TotalPrice = this._GetNewTotalPriceAndCount(this.App.CartList).totalPrice;
            this.Data.Count = this._GetNewTotalPriceAndCount(this.App.CartList).count;
            this.Data.ApplyChange(this);
            wx.hideToast();
        } catch (e) {
            this.ShowError(e);
        } finally {
            wx.hideLoading();
        }
    }

    /**
     * 减少商品数量
     * @param {*} e
     * @returns {Promise<void>}
     * @memberof IndexPage
     */
    public async DecreaseCountHandler(e: any): Promise<void> {
        try {
            let cart: V_Cart = this.Data.CartList[e.currentTarget.dataset.index];
            if (cart.GOODSNUM <= 1) {
                this.Data.CartList[e.currentTarget.dataset.index].GOODSNUM = 1;
                this.Data.ApplyChange(this);
            } else {
                cart.GOODSNUM--;
                await NS.UpdateCartCount(cart.ID, cart.GOODSNUM);
                this.Data.CartList[e.currentTarget.dataset.index] = cart;
                this.Data.TotalPrice = this._GetNewTotalPriceAndCount(
                    this.Data.CartList
                ).totalPrice;
                this.Data.Count = this._GetNewTotalPriceAndCount(this.Data.CartList).count;
                this.Data.CartList = this.Data.CartList;
                this.Data.ApplyChange(this);
            }
        } catch (e) {
            this.ShowError(e);
        }
    }

    /**
     * 增加商品数量
     * @param {*} e
     * @returns {Promise<void>}
     * @memberof IndexPage
     */
    public async IncreaseCountHandler(e: any): Promise<void> {
        try {
            let cart: V_Cart = this.Data.CartList[e.currentTarget.dataset.index];
            cart.GOODSNUM++;
            await NS.UpdateCartCount(cart.ID, cart.GOODSNUM);
            this.Data.CartList[e.currentTarget.dataset.index] = cart;
            this.Data.TotalPrice = this._GetNewTotalPriceAndCount(this.Data.CartList).totalPrice;
            this.Data.Count = this._GetNewTotalPriceAndCount(this.Data.CartList).count;
            this.Data.CartList = this.Data.CartList;
            this.Data.ApplyChange(this);
        } catch (e) {
            this.ShowError(e);
        }
    }

    /**
     * 清空失效商品
     * @param {*} e
     * @returns {Promise<void>}
     * @memberof IndexPage
     */
    public async EmptyHandler(e: any): Promise<void> {
        try {
            let r: boolean = await this.App.Wx_ShowModal("提示", "确认清空失效商品吗？", true);
            if (r == true) {
                //用户点击确认
                let CartIdArr: number[] = [];
                let cartList: V_Cart[] = [];
                this.Data.CartList.forEach(el => {
                    if (el.GOODSSTATUS == 3 || el.GOODSSTATUS == 4) CartIdArr.push(el.ID);
                    else cartList.push(el);
                });
                await NS.DeleteCartList(CartIdArr);
                this.Data.CartList = cartList;
                this.Data.ApplyChange(this);
            }
        } catch (e) {
            this.ShowError(e);
        }
    }

    /**
     * 删除商品
     * @param {*} e
     * @returns {Promise<void>}
     * @memberof IndexPage
     */
    public async DeleteCartHandler(e: any): Promise<void> {
        try {
            let r: boolean = await this.App.Wx_ShowModal("提示", "确认删除该商品吗？", true);
            if (r == true) {
                //用户点击确认
                let cartId: number = e.currentTarget.dataset.cartid;
                await NS.DeleteCart(cartId);
                let cartList: V_Cart[] = [];
                this.Data.CartList.forEach(el => {
                    if (cartId != el.ID) {
                        cartList.push(el);
                    }
                });
                this.Data.CartList = cartList;
                this.Data.TotalPrice = this._GetNewTotalPriceAndCount(cartList).totalPrice;
                this.Data.Count = this._GetNewTotalPriceAndCount(cartList).count;
                this.Data.ApplyChange(this);
            }
        } catch (e) {
            this.ShowError(e);
        }
    }

    /**
     * 批量删除所有选中商品
     * @param {*} e
     * @returns {Promise<void>}
     * @memberof IndexPage
     */
    public async DelSeletedHandler(e: any): Promise<void> {
        try {
            let r: boolean = await this.App.Wx_ShowModal("提示", "确认删除所有选中商品吗？", true);
            let cartIdArr: number[] = []; //需要删除的商品Id
            let cartList: V_Cart[] = []; //不用删除的商品
            if (r == true) {
                //用户点击确认
                this.Data.CartList.forEach(el => {
                    if ((el.GOODSSTATUS == 1 || el.GOODSSTATUS == 2) && el.ISSELECT)
                        cartIdArr.push(el.ID);
                    else cartList.push(el);
                });
                await NS.DeleteCartList(cartIdArr);
                this.Data.CartList = cartList;
                this.Data.TotalPrice = this._GetNewTotalPriceAndCount(cartList).totalPrice;
                this.Data.Count = this._GetNewTotalPriceAndCount(cartList).count;
                this.Data.ApplyChange(this);
            }
        } catch (e) {
            this.ShowError(e);
        }
    }

    /**
     * 修改购物车选中状态
     * @param {*} e
     * @returns {Promise<void>}
     * @memberof IndexPage
     */
    public async CartSelectStateHandler(e: any): Promise<void> {
        try {
            let CartId: number = e.currentTarget.dataset.id;
            let State: boolean = e.currentTarget.dataset.isselect;
            let cartList: V_Cart[] = this.Data.CartList;
            //AllSelected是否为True
            let allSelected: boolean = true;
            cartList.forEach(el => {
                if (el.ID == CartId) {
                    el.ISSELECT = !State;
                }
                if (el.GOODSSTATUS == 1 && !el.ISSELECT) {
                    allSelected = false;
                }
            });
            await NS.UpdateCartSelectState(CartId, !State);
            this.Data.CartList = cartList;
            this.Data.AllSelected = allSelected;
            this.Data.TotalPrice = this._GetNewTotalPriceAndCount(cartList).totalPrice;
            this.Data.Count = this._GetNewTotalPriceAndCount(cartList).count;
            this.Data.ApplyChange(this);
        } catch (e) {
            this.ShowError(e);
        }
    }

    /**
     * 修改全部可购商品全选全不选
     * @param {*} e
     * @returns {Promise<void>}
     * @memberof IndexPage
     */
    public async CartSelectAllHandler(e: any): Promise<void> {
        try {
            let CartIdArr: number[] = [];
            let State: boolean = !this.Data.AllSelected;
            let cartList: V_Cart[] = this.Data.CartList;
            cartList.forEach(el => {
                if (el.GOODSSTATUS == 1) {
                    CartIdArr.push(el.ID);
                    el.ISSELECT = State;
                }
            });
            await NS.UpdateCartSelectAll(CartIdArr, State);
            this.Data.AllSelected = State;
            this.Data.CartList = cartList;
            this.Data.TotalPrice = this._GetNewTotalPriceAndCount(cartList).totalPrice;
            this.Data.Count = this._GetNewTotalPriceAndCount(cartList).count;
            this.Data.ApplyChange(this);
        } catch (e) {
            this.ShowError(e);
        }
    }

    /**
     * 编辑
     * @param {*} e
     * @memberof IndexPage
     */
    public EditHandler(e: any): void {
        if (this.Data.flag == false) {
            this.Data.flag = true;
            this.Data.ApplyChange(this);
        }
    }

    /**
     * 编辑完成
     * @param {*} e
     * @memberof IndexPage
     */
    public FinishHandler(e: any): void {
        if (this.Data.flag == true) {
            this.Data.flag = false;
            this.Data.ApplyChange(this);
        }
    }

    /**
     * 商品详情？？？
     * @param {*} e
     * @memberof IndexPage
     */
    public NxetHandler(e: any): void {
        try {
            let type = e.currentTarget.dataset.type;
            let id = e.currentTarget.dataset.id;
            let cardbill = e.currentTarget.dataset.cardbill;
            wx.navigateTo({
                url: "../ProductClass/Product"
            });
        } catch (e) {}
    }

    /**
     * 结算
     * @param {*} e
     * @memberof IndexPage
     */
    public AccountHandler(e: any): void {
        try {
            //this.BuildingHandler();
            //console.log(e, "ssssssssssssssssssssssssssssssssssssssssssss");
            wx.navigateTo({ url: "../FirmOrder/Index" });
        } catch (e) {
            this.ShowError(e);
        }
    }

    /**
     * 结算
     * @param {*} e
     * @memberof IndexPage
     */
    public SettlementHandler(e: any): void {
        try {
        } catch (e) {
            this.ShowError(e);
        }
    }

    /**
     * 获取最新的总价和商品数量
     * @private
     * @param {V_Cart[]} cartList
     * @returns {*}
     * @memberof IndexPage
     */
    private _GetNewTotalPriceAndCount(cartList: V_Cart[]): any {
        let totalPrice: number = 0;
        let count: number = 0;
        cartList.forEach(el => {
            if (el.GOODSSTATUS == 1 && el.ISSELECT) {
                totalPrice += el.SKU.PRICE * el.GOODSNUM;
                count++;
            }
        });
        return { totalPrice, count };
    }
}

Page(new IndexPage());
